import React, { useState, useEffect } from 'react';
import { Layout } from './components/Layout/Layout';
import { Login } from './pages/Login';
import { Orders } from './pages/Orders';
import { CargoPage } from './pages/Cargo';
import { Analytics } from './pages/Analytics';

type PageType = '/orders' | '/cargo' | '/analytics';

const App: React.FC = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [currentUser, setCurrentUser] = useState<string | null>(null);
  const [currentEmail, setCurrentEmail] = useState<string | null>(null);
  const [currentPage, setCurrentPage] = useState<PageType>('/analytics'); // 默认显示数据分析大屏

  // 检查本地存储中的登录状态
  useEffect(() => {
    const savedLoginState = localStorage.getItem('isLoggedIn');
    const savedUser = localStorage.getItem('currentUser');
    const savedEmail = localStorage.getItem('currentEmail');
    
    if (savedLoginState === 'true' && savedUser) {
      setIsLoggedIn(true);
      setCurrentUser(savedUser);
      setCurrentEmail(savedEmail);
    }
  }, []);

  const handleLogin = (username: string, email?: string) => {
    setIsLoggedIn(true);
    setCurrentUser(username);
    setCurrentEmail(email || null);
    setCurrentPage('/analytics'); // 登录后跳转到数据分析大屏
    
    // 保存登录状态到本地存储
    localStorage.setItem('isLoggedIn', 'true');
    localStorage.setItem('currentUser', username);
    if (email) {
      localStorage.setItem('currentEmail', email);
    }
  };

  const handleLogout = () => {
    setIsLoggedIn(false);
    setCurrentUser(null);
    setCurrentEmail(null);
    setCurrentPage('/analytics');
    
    // 清除本地存储
    localStorage.removeItem('isLoggedIn');
    localStorage.removeItem('currentUser');
    localStorage.removeItem('currentEmail');
  };

  const handleNavigate = (path: string) => {
    setCurrentPage(path as PageType);
    // 页面切换后滚动到顶部
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  // 监听页面变化，确保滚动到顶部
  useEffect(() => {
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, [currentPage]);

  const renderPage = () => {
    switch (currentPage) {
      case '/orders':
        return <Orders />;
      case '/cargo':
        return <CargoPage />;
      case '/analytics':
        return <Analytics />;
      default:
        return <Analytics />; // 默认显示数据分析大屏
    }
  };

  // 如果未登录，显示登录页面
  if (!isLoggedIn) {
    return <Login onLogin={handleLogin} />;
  }

  return (
    <Layout 
      currentPath={currentPage} 
      onNavigate={handleNavigate}
      currentUser={currentUser}
      currentEmail={currentEmail}
      onLogout={handleLogout}
    >
      {renderPage()}
    </Layout>
  );
};

export default App;